import {
  getTenantList,
  addTenant,
  editTenant,
  delTenant,
  queryTenant,
  listUsers,
  submitUsers,
  getAuthorizedApp,
} from "../server/TenantManagementApi";

const initData = {
  tenantList: [],
  totalCount: 0,
};

export default {
  namespace: "tenantManagement",
  state: {
    ...initData,
  },

  effects: {
    *getTenantList({ payload }, { call, put }) {
      const { errCode, errortext: errMsg, datas = [], totalCount } = yield call(
        getTenantList,
        payload,
      );
      yield put({ type: "get/tenantList", payload: datas, totalCount });
      return { errCode, errMsg, datas };
    },
    *addTenant({ payload }, { call }) {
      const { errCode, errortext: errMsg } = yield call(addTenant, payload);
      // console.log('result: ', result);
      return { errCode, errMsg };
    },
    *editTenant({ payload }, { call }) {
      const { errCode, errortext: errMsg } = yield call(editTenant, payload);
      return { errCode, errMsg };
    },
    *delTenant({ payload }, { call }) {
      const { errCode, errMsg, errortext } = yield call(delTenant, payload);
      return { errCode, errMsg: errMsg || errortext };
    },
    *queryTenant({ payload }, { call }) {
      const { errCode, errMsg, errortext, datas } = yield call(queryTenant, payload);
      return { errCode, errMsg: errMsg || errortext, datas };
    },
    *listUsers({ payload }, { call }) {
      const { errCode, errMsg, errortext, datas } = yield call(
        listUsers,
        payload,
      );
      return { errCode, errMsg: errMsg || errortext, datas };
    },
    *submitUsers({ payload }, { call }) {
      const { errCode, errMsg, errortext } = yield call(submitUsers, payload);
      return { errCode, errMsg: errMsg || errortext };
    },
    *delTenantUser({ payload: { tenantId, userCode, id } }, { call }) {
      const { errCode, errMsg, errortext } = yield call(submitUsers, { tenantId, delCol: [{ userCode, id }] });
      return { errCode, errMsg: errMsg || errortext };
    },
    *getAuthorizedApp({ payload }, { call }) {
      const { errCode, errMsg, errortext, datas } = yield call(
        getAuthorizedApp,
        payload,
      );
      return { errCode, errMsg: errMsg || errortext, datas };
    },
  },
  reducers: {
    "get/tenantList": (state, { payload, totalCount }) => ({
      ...state,
      tenantList: payload,
      totalCount,
    }),
    clearData: () => ({ ...initData }),
  },
};
